from loguru import logger

from com.arcfox.school.processor.base_processor import BaseProcessor, ImgType
from com.arcfox.middleware import async_mysql_middleware as db


class YunVRProcessor(BaseProcessor):
    def __init__(self):
        self.base_url = "https://720yun.com/t/"
        self.URL_SOURCE = "720yun"

    async def parse_and_save_data(self, task, result_json):
        data = result_json['data']
        if data['count'] > 0:
            data_list = data['list']
            matched_data = self.filter_data(task['name'], data_list)
            mapping = db.MysqlMapping("tb_university_img")
            for item in matched_data:
                data_id = item['dataId']
                name = item['name']
                full_url = f"{self.base_url}{data_id}?scene_id={item['id']}"
                result = await mapping.query({"university_uid": task['uid'], "img_url": full_url}, ["id"])
                if result:
                    logger.info("图片已存在!")
                else:
                    data = {
                        "university_uid": task['uid'],
                        "university_name": task['name'],
                        "img_url": full_url,
                        "img_type": ImgType.VR.value,
                        "img_desc": name,
                        "img_source": self.URL_SOURCE,
                    }
                    await mapping.insert(data)

    def filter_data(self, university_name, data_list):
        matched_data = list(filter(lambda o: o['name'] == university_name, data_list))
        if not matched_data:
            matched_data = list(filter(lambda o: university_name in o['name'], data_list))
        if matched_data and len(matched_data) > 3:
            matched_data = matched_data[0:3]
        return matched_data
